# -*- coding:utf-8 -*-
import sys
from matplotlib import pyplot as plt
import cv2 as cv
import numpy as np


if __name__ == '__main__':


    image = cv.imread(r"E:\studylife\detectflaws\code\imgEnhance\img.jpg", cv.IMREAD_GRAYSCALE)

    # 绘制原图直方图
    plt.hist(image.ravel(), 256, [0, 256])
    plt.title('Origin Image')
    plt.show()
    # 进行均衡化并绘制直方图
    # image_result = cv.equalizeHist(image)  # 普通直方图均衡化
    # 自适应直方图均衡化
    clahe = cv.createCLAHE(clipLimit=25, tileGridSize=(2, 2))  # clipLimit：这是对比度限制的阈值
    image_result = clahe.apply(image)  # tileGridSize：将输入图像划分为M × N块，然后对每个局部块应用直方图均衡化

    image = cv.resize(image, (640, 480))
    image_result = cv.resize(image_result, (640, 480))

    plt.hist(image_result.ravel(), 256, [0, 256])
    plt.title('Equalized Image')
    plt.show()
    # 展示均衡化前后的图片
    cv.imshow('Origin Image', image)
    cv.imshow('Equalized Image', image_result)


    #轮廓检测

    # 高斯滤波
    gauss = cv.GaussianBlur(image_result, (9, 9), sigmaX=2, sigmaY=2)
    cv.imshow('gauss', gauss)


    # 灰度图像大律法二值化
    _, img1_O = cv.threshold(image, 250, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)

    cv.imshow('img1_O', img1_O)


    # 轮廓检测
    contours, hierarchy = cv.findContours(img1_O, mode=cv.RETR_TREE, method=cv.CHAIN_APPROX_SIMPLE)

    # 轮廓绘制
    image_result2 = cv.drawContours(image, contours, -1, (0, 0, 255), 3, 8)

    # 输出轮廓结构关系
    print(hierarchy)
    cv.imshow('Find and Draw Contours', image_result2)

    cv.waitKey(0)
    cv.destroyAllWindows()
